package com.example.fmgidsprototype;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.fmgidsprototype.data.DataManager;
import com.example.fmgidsprototype.model.Review;
import com.example.fmgidsprototype.model.Venue;

public class DetailSliderActivity extends FragmentActivity{
	
	private static int NUM_PAGES = 0;
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;
    private FmGidsPrototypeApp app;
    private InputStream stream;
    private DataManager dm;
    private ProgressDialog progressDialog;
    private SharedPreferences prefs;
    private List<Venue> venues;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_slide);
        // Instantiate a ViewPager and a PagerAdapter.
        app = (FmGidsPrototypeApp)getApplication();
        dm = app.getDataManager();
        String selectedCategoryText = app.getSelectedCategoryName();
        if(selectedCategoryText == null || !selectedCategoryText.equals("All Venues")){
        	TextView detailBarText = (TextView)findViewById(R.id.bar_filter_indicator);
            detailBarText.setText(selectedCategoryText);
        }
        
        prefs = getSharedPreferences(AppConstants.PREFS_IDENTIFIER, Context.MODE_PRIVATE);
        
        progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Information is been updated; please have patience.");
		progressDialog.setIndeterminate(false);
		progressDialog.setMax(100);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		   
	    venues = app.getCategoryVenues();
	    //if there was no category selected => show all
	    if(venues.size() == 0)
	    	venues = app.getAllVenues();
	    Log.d("VENUESoutASYNC", "nr out async: " + venues.size());
	    //now get the jsondata if needed
	    String url = AppConstants.REVIEW_JSON_PATH;
	    
	    if(!this.jsonExists() || this.checkForNewJson(url)){
	  		new ReviewJsonDownloader().execute(url);
	  	}
	    new ReviewDownloader().execute();
        NUM_PAGES = venues.size();
        
        // set icon fonts
        Typeface iconFont = Typeface.createFromAsset(getAssets(), "icomoon.ttf");
		Button homeBtn = (Button) findViewById(R.id.bar_home_btn);
		homeBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(DetailSliderActivity.this, VenuesList.class);
				startActivity(intent);
			}
		});
		homeBtn.setTypeface(iconFont);
		Button settingsBtn = (Button) findViewById(R.id.bar_settings_btn);
		settingsBtn.setTypeface(iconFont);
		Button infoBtn = (Button) findViewById(R.id.bar_info_btn);
		infoBtn.setTypeface(iconFont);
        
    }
    
    
    //TODO move this to Util cause it's a copy of method in VenuesList
    private boolean checkForNewJson(String urlString){
		//TODO check if there is a newer version
		long localTimeStamp = prefs.getLong(AppConstants.JSON_VENUE_DATE, 0L);
		JsonLastModifiedCheck jsonCheck = new JsonLastModifiedCheck();
		jsonCheck.execute(AppConstants.VENUE_JSON_PATH);
		long remoteTimeStamp = jsonCheck.getRemoteTimeStamp();
		Log.d("TIME", "local: " + localTimeStamp + " and remote: " + remoteTimeStamp);
		return Util.mustUpdate(localTimeStamp, remoteTimeStamp);
	}

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
        	mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }
    
    private boolean jsonExists(){
		try{
			InputStream in = openFileInput(AppConstants.JSON_REVIEWS_FILE);
		}
		catch(FileNotFoundException fnf){
			return false;
		}
		return true;
	}
 
    private class ReviewDownloader extends AsyncTask<Void, Integer, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			Log.d("VENUESINASYNC", "nr in async: " + venues.size());
			for(Venue v : venues){
				List<Review> reviews = dm.getReviewsForVenue(v.getJsonId());
				v.setReviews(reviews);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			 mPager = (ViewPager) findViewById(R.id.pager);
			 mPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), venues, 
					 DetailSliderActivity.this, dm);
			 mPager.setAdapter(mPagerAdapter);
			 mPager.setCurrentItem(app.getCurrentSelectedVenue(), true);
		}
    	
    }
    
    private class ReviewJsonDownloader extends AsyncTask<String, Integer, String>{
		
		private InputStream input;
		private FileOutputStream output;
		private URLConnection conn;
		private URL url;
		private long remoteTimeStamp;
		private boolean mustUpdate = false;
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			try{
				stream = openFileInput(AppConstants.JSON_REVIEWS_FILE);
				ReviewJsonReader jReader = new ReviewJsonReader(stream, DetailSliderActivity.this.dm);
				jReader.writeToDb();
			}
			catch(Exception e){
				
			}finally{
				try{
					stream.close();
					String resourceName = AppConstants.JSON_REVIEW_DATE;
					DetailSliderActivity.this.updateTimeStamp(new Date().getTime(), resourceName);
				}
				catch(Exception ee){}
				progressDialog.dismiss();
			}	
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
				super.onProgressUpdate(values);
				progressDialog.setProgress(values[0]);
		}

		@Override
		protected String doInBackground(String...params) {
				JSONObject json = null;
				try{
					String urlString = params[0];
					url = new URL(urlString);
					conn = url.openConnection();
					conn.setConnectTimeout(3000);
			        conn.setReadTimeout(5000);
			        conn.connect();
			        int length = conn.getContentLength();
			        input = new BufferedInputStream(conn.getInputStream());
			        //create json file in internal storage
			        output = openFileOutput(AppConstants.JSON_REVIEWS_FILE, Context.MODE_PRIVATE);
			        int read = 0;
			        long total = 0;
			        byte[] bytes = new byte[1024];  
			        while ((read = input.read(bytes)) != -1) {
			        	total += read;
			        	publishProgress((int)(total * 100 / length));
			        	output.write(bytes, 0, read);
			        }		        
				}
				catch(IOException ioe){
					
				}
				finally{
					try{
						output.flush();
						input.close();
						output.close();
					}
					catch(Exception oe){	
					}
				}
				return null;
		}	

	}

    
    public void updateTimeStamp(long timeStamp, String resourceName){
		long current = prefs.getLong(resourceName, 0L);
		Editor editor = prefs.edit();
		if(current != 0L){
			editor.remove(resourceName);
		}
		editor.putLong(resourceName, timeStamp);
	}

}
